package com.zc.basic.app.controller;

import com.zc.basic.app.service.PcmcMenuService;
import com.zc.basic.domain.dto.MenuDto;
import com.zc.basic.domain.dto.MenuNode;
import com.zc.basic.domain.pojo.PcmcMenu;
import com.zc.basic.infra.mapper.MenuDtoMapper;
import com.zc.basic.infra.mapper.MenuNodeMapper;
import com.zc.commons.pojo.AuthenticatedUser;
import com.zc.commons.pojo.ResponseData;
import com.zc.commons.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/menu")
public class MenuController {

    @Autowired
    private MenuDtoMapper menuDtoMapper;
    @Autowired
    private MenuNodeMapper menuNodeMapper;
    @Autowired
    private PcmcMenuService pcmcMenuService;

    @RequestMapping(value = "/userMenus", method = {RequestMethod.GET, RequestMethod.POST})
    public List<MenuDto> queryUserMenus() {

        AuthenticatedUser currentUser = UserUtil.getCurrentUser();

        List<MenuDto> menuDtos = menuDtoMapper.queryUserRoleMenu(currentUser.getUserCode());
        return menuDtos;
    }

    @PostMapping(value = "/menuNodeTree")
    public List<MenuNode> queryMenuNode(@RequestBody PcmcMenu pcmcMenu) {
        List<MenuNode> menuNodes = menuNodeMapper.queryMenuNodeTree(pcmcMenu);
        return menuNodes;
    }

    @RequestMapping(value = "/info", method = {RequestMethod.GET, RequestMethod.POST})
    public PcmcMenu querySingleMenu(@RequestParam Integer id) {
        PcmcMenu pcmcMenu = pcmcMenuService.getById(id);
        return pcmcMenu;
    }

    @PostMapping(value = "/add")
    public ResponseData<PcmcMenu> addMenu(@RequestBody PcmcMenu pcmcMenu) {
        boolean save = pcmcMenuService.save(pcmcMenu);
        if (!save) {
            return ResponseData.error("系统异常，操作失败！");
        }
        return ResponseData.ok("添加成功！", pcmcMenu);
    }

    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData deleteMenu(@RequestParam Integer id) {
        int code = 200;
        String message = "删除成功！";
        int delete = pcmcMenuService.deleteMenu(id);
        if (delete == 0) {
            code = 300;
            message = "系统异常，操作数据不存在！";
        }
        return new ResponseData(code, message);
    }

    @PostMapping(value = "/update")
    public ResponseData update(@RequestBody PcmcMenu pcmcMenu) {
        int code = 200;
        String message = "修改成功！";
        boolean save = pcmcMenuService.updateById(pcmcMenu);
        if (!save) {
            code = 300;
            message = "系统异常，修改失败！";
        }
        return new ResponseData(code, message, pcmcMenu);
    }


}
